<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户设置</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>

    <hr />

    <el-tabs type="border-card" value="first" @tab-click="handleClick">
      <!-- 分院管理 -->
      <el-tab-pane label="分院管理" name="first">
        <!-- 搜索区域 -->
        <el-row :gutter="20">
          <el-col :span="5">
            <el-select
              v-model="queryInfo.query"
              placeholder="请选择分院"
              clearable
              @clear="getDeptList"
              @change="getDeptList"
            >
              <el-option
                v-for="item in allDept"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptName"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>

        <!-- 功能区域 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true"
              >添加分院</el-button
            >
          </el-col>
        </el-row>

        <!-- 分院列表区域 -->
        <el-table :data="deptList" border stripe style="width: 100%">
          <el-table-column
            prop="deptId"
            label="分院编号"
            width="100px"
          ></el-table-column>
          <el-table-column
            prop="deptName"
            label="分院名称"
            sortable
          ></el-table-column>
          <el-table-column prop="leader" label="负责人"></el-table-column>
          <el-table-column
            prop="tecCount"
            label="在校教职工人数"
          ></el-table-column>
          <el-table-column
            prop="stuCount"
            label="在校学生人数"
          ></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <!-- 修改 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                plain
                @click="showEditDialog(scope.row.deptId)"
                >编辑</el-button
              >
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                plain
                @click="
                  removeDialog(
                    scope.row.tecCount,
                    scope.row.stuCount,
                    scope.row.deptId
                  )
                "
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="queryInfo.page"
          :page-size="queryInfo.size"
          layout="total, prev, pager, next"
          :total="total"
          background
        ></el-pagination>
      </el-tab-pane>

      <!-- 添加分院对话框 -->
      <el-dialog
        title="添加分院"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 内容主体区域 -->
        <el-form
          ref="addFormRef"
          :rules="addFormRules"
          :model="addForm"
          label-width="100px"
        >
          <el-form-item label="分院名称" prop="deptName">
            <el-input v-model="addForm.deptName"></el-input>
          </el-form-item>

          <el-form-item label="负责人" prop="leader">
            <el-input v-model="addForm.leader"></el-input>
          </el-form-item>

          <el-form-item label="负责人编号" prop="leaderId">
            <el-input v-model="addForm.leaderId"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="addForm.phone"></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDept">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改分院对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="width"
        @close="editDialogClosed"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="120px"
        >
          <el-form-item label="分院名称">
            <el-input v-model="editForm.deptName" disabled></el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-switch
              v-model="editForm.status"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>

          <el-form-item label="负责人" prop="leader">
            <el-input v-model="editForm.leader"></el-input>
          </el-form-item>

          <el-form-item label="负责人身份证" prop="leaderId">
            <el-input v-model="editForm.leaderId"></el-input>
          </el-form-item>

          <el-form-item label="电话" prop="phone">
            <el-input v-model="editForm.phone"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateEdit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 删除分院警告框 -->
      <el-dialog title="警告" :visible.sync="delDialogVisible" width="30%">
        <span>您确定要删除此条分院信息吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="delDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="delById">确 定</el-button>
        </span>
      </el-dialog>

      <!-- ----------------------------------------- 班级管理 ----------------------------------------- -->
      <el-tab-pane label="班级管理" name="second">
        <!-- 搜索区域 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-input
              placeholder="请输入班级"
              v-model="queryClass.deptClass"
              class="input-with-select"
            >
              <el-select
                v-model="queryClass.deptParent"
                slot="prepend"
                placeholder="请选择分院"
                clearable
              >
                <el-option
                  v-for="item in allDept"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptName"
                >
                </el-option>
              </el-select>
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getClsList"
              ></el-button>
            </el-input>
          </el-col>
        </el-row>

        <!-- 功能区域 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="primary" @click="addClsDialogVisible = true"
              >添加班级</el-button
            >
          </el-col>
        </el-row>

        <!-- 班级列表区域 -->
        <el-table :data="classList" border stripe style="width: 100%">
          <el-table-column prop="deptId" label="班级编号"></el-table-column>
          <el-table-column
            prop="parentDept"
            label="分院名称"
            sortable
          ></el-table-column>
          <el-table-column
            prop="deptName"
            label="班级名称"
            sortable
          ></el-table-column>
          <el-table-column prop="leader" label="班主任"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <!-- 修改 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                plain
                @click="showClsEditDialog(scope.row.deptId)"
                >编辑</el-button
              >
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                plain
                @click="removeClsDialog(scope.row.deptId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @current-change="handleClsCurrentChange"
          :current-page.sync="queryClass.page"
          :page-size="queryClass.size"
          layout="total, prev, pager, next"
          :total="totalClass"
          background
        ></el-pagination>
      </el-tab-pane>

      <!-- 添加班级对话框 -->
      <el-dialog
        title="添加班级"
        :visible.sync="addClsDialogVisible"
        width="50%"
        @close="addClsDialogClosed"
      >
        <!-- 内容主体区域 -->
        <el-form
          ref="addClsFormRef"
          :rules="addClsFormRules"
          :model="addClsForm"
          label-width="100px"
        >
          <el-form-item label="分院名称" prop="parentId">
            <el-select
              v-model="addClsForm.parentId"
              placeholder="请选择分院"
              clearable
            >
              <el-option
                v-for="item in allDept"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班级名称" prop="deptName">
            <el-input v-model="addClsForm.deptName"></el-input>
          </el-form-item>

          <el-form-item label="班主任" prop="leader">
            <el-input v-model="addClsForm.leader"></el-input>
          </el-form-item>

          <el-form-item label="身份证编号" prop="leaderId">
            <el-input v-model="addClsForm.leaderId"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addClsForm.email"></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="addClsForm.phone"></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addClsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addClsDept">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改班级对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editClsDialogVisible"
        width="width"
        @close="editClsDialogClosed"
      >
        <el-form
          ref="editClsFormRef"
          :model="editClsForm"
          :rules="editClsFormRules"
          label-width="120px"
        >
          <el-form-item label="分院名称">
            <el-select
              v-model="editClsForm.parentDept"
              placeholder="placeholder"
              disabled
            >
              <el-option
                :label="editClsForm.parentDept"
                :value="editClsForm.parentId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="班级名称">
            <el-input
              v-model="editClsForm.deptName"
              :value="editClsForm.deptId"
              disabled
            ></el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-switch
              v-model="editClsForm.status"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>

          <el-form-item label="班主任" prop="leader">
            <el-input v-model="editClsForm.leader"></el-input>
          </el-form-item>

          <el-form-item label="班主任身份证" prop="leaderId">
            <el-input v-model="editClsForm.leaderId"></el-input>
          </el-form-item>

          <el-form-item label="电话" prop="phone">
            <el-input v-model="editClsForm.phone"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editClsForm.email"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="editClsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateClsEdit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 删除班级警告框 -->
      <el-dialog title="警告" :visible.sync="delClsDialogVisible" width="30%">
        <span>您确定要删除此条班级信息吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="delClsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="delClsById">确 定</el-button>
        </span>
      </el-dialog>
    </el-tabs>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('邮箱格式有误'))
    }

    // 验证手机号
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('手机号输入错误'))
    }

    // 验证身份证号
    var checkLeaderId = (rule, value, cb) => {
      // const reg = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      const reg = /^[0-9]{18}$/
      if (reg.test(value)) {
        return cb()
      }
      cb(new Error('身份证号输入有误'))
    }

    return {
      allDept: [],
      deptList: [],
      queryInfo: {
        query: '',
        page: 1,
        size: 10
      },
      total: 0,
      addDialogVisible: false,
      addForm: {
        deptName: '',
        leader: '',
        leaderId: '',
        email: '',
        phone: '',
        createBy: ''
      },
      addFormRules: {
        deptName: [
          {
            required: true,
            message: '请输入分院名称',
            trigger: 'blur'
          }
        ],
        leader: [
          {
            required: true,
            message: '请输入负责人姓名',
            trigger: 'blur'
          }
        ],
        leaderId: [
          {
            required: true,
            message: '请输入负责人身份证编号',
            trigger: 'blur'
          },
          {
            validator: checkLeaderId,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      editDialogVisible: false,
      editForm: {
        deptId: 0,
        parentId: 0,
        deptName: '',
        status: '',
        leader: '',
        leaderId: '',
        phone: '',
        email: '',
        updateBy: ''
      },
      editFormRules: {
        leader: [
          {
            required: true,
            message: '请输入负责人姓名',
            trigger: 'blur'
          }
        ],
        leaderId: [
          {
            required: true,
            message: '请输入负责人身份证编号',
            trigger: 'blur'
          },
          {
            validator: checkLeaderId,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      delDialogVisible: false,
      delId: 0,
      // ----------------------- 以下为班级管理 -----------------------
      classList: [],
      queryClass: {
        deptParent: '',
        deptClass: '',
        page: 1,
        size: 10
      },
      totalClass: 0,
      addClsDialogVisible: false,
      addClsForm: {
        parentId: '',
        deptName: '',
        leader: '',
        leaderId: '',
        email: '',
        phone: '',
        createBy: ''
      },
      addClsFormRules: {
        parentId: [
          {
            required: true,
            message: '请选择分院',
            trigger: 'blur'
          }
        ],
        deptName: [
          {
            required: true,
            message: '请输入班级名称',
            trigger: 'blur'
          }
        ],
        leader: [
          {
            required: true,
            message: '请输入班主任姓名',
            trigger: 'blur'
          }
        ],
        leaderId: [
          {
            required: true,
            message: '请输入班主任身份证编号',
            trigger: 'blur'
          },
          {
            validator: checkLeaderId,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      editClsDialogVisible: false,
      editClsForm: {
        deptId: 0,
        parentDept: '',
        parentId: '',
        deptName: '',
        status: '',
        leader: '',
        leaderId: '',
        phone: '',
        email: '',
        updateBy: ''
      },
      editClsFormRules: {
        leader: [
          {
            required: true,
            message: '请输入班主任姓名',
            trigger: 'blur'
          }
        ],
        leaderId: [
          {
            required: true,
            message: '请输入班主任身份证编号',
            trigger: 'blur'
          },
          {
            validator: checkLeaderId,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      delClsDialogVisible: false
    }
  },
  created() {
    this.getDeptList()
    this.getAllDept()
  },
  methods: {
    async getAllDept() {
      const { data: res } = await this.$http.get('dept/allDept')
      if (res.code !== 20000) {
        return this.$message.error('分院列表获取失败!')
      }
      this.allDept = res.data
    },
    async getDeptList() {
      const { data: res } = await this.$http.get('dept/list', {
        params: this.queryInfo
      })
      if (res.code !== 20000) {
        return this.$message.error('获取列表信息失败')
      }
      this.deptList = res.data.list
      this.total = res.data.total
    },
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.getDeptList()
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加分院
    addDept() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        this.addForm.createBy = window.sessionStorage.getItem('rootname')
        const { data: res } = await this.$http.post('dept/add', this.addForm)
        if (res.code === 20005) return this.$message.error('分院名称重复!')
        else if (res.code === 20006) {
          return this.$message.error('未找到负责人信息!')
        } else if (res.code === 20000) {
          this.addDialogVisible = false
          this.getDeptList()
          this.getAllDept()
          return this.$message.success('添加成功')
        }
      })
    },
    // 展示编辑分院的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('dept/one/' + id)
      if (res.code !== 20000) {
        return this.$message.error('查询用户信息失败!')
      }
      this.editForm = res.data
      // if (this.editForm.status === '1') {
      //   this.editForm.status = true
      // } else {
      //   this.editForm.status = false
      // }
      this.editDialogVisible = true
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    updateEdit() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        this.editForm.updateBy = window.sessionStorage.getItem('rootname')
        // 设置开关状态按钮
        // if (this.editForm.status === true) {
        //   this.editForm.status = '1'
        // } else {
        //   this.editForm.status = '0'
        // }
        const { data: res } = await this.$http.put('dept/update', this.editForm)
        if (res.code !== 20000) {
          return this.$message.error('更新信息失败!')
        }
        this.editDialogVisible = false
        this.getDeptList()
        this.$message.success('更新信息成功!')
      })
    },
    handleClick(tab) {
      if (tab.name === 'first') {
        this.queryInfo.query = ''
        this.getDeptList()
      } else {
        this.getClsList()
      }
    },
    // 通过ID删除分院信息
    removeDialog(tecCount, stuCount, id) {
      if (tecCount + stuCount > 0) {
        return this.$message.error('不可删除：该分院仍存在师生!')
      }
      this.delId = id
      this.delDialogVisible = true
    },
    async delById() {
      const { data: res } = await this.$http.delete('dept/del/' + this.delId)
      if (res.code !== 20000) {
        return this.$message.error('删除分院信息失败!')
      }
      this.delDialogVisible = false
      this.getDeptList()
      this.getAllDept()
      this.$message.success('删除分院信息成功!')
    },
    // ----------------------- 以下为班级管理 -----------------------
    async getClsList() {
      const { data: res } = await this.$http.get('dept/clss', {
        params: this.queryClass
      })
      if (res.code !== 20000) {
        return this.$message.error('获取列表信息失败')
      }
      this.classList = res.data.list
      this.totalClass = res.data.total
    },
    handleClsCurrentChange(newPage) {
      this.queryClass.page = newPage
      this.getClsList()
    },
    addClsDialogClosed() {
      this.$refs.addClsFormRef.resetFields()
    },
    // 添加班级
    addClsDept() {
      this.$refs.addClsFormRef.validate(async valid => {
        if (!valid) return
        this.addClsForm.createBy = window.sessionStorage.getItem('rootname')
        const { data: res } = await this.$http.post('dept/add', this.addClsForm)
        if (res.code === 20005) return this.$message.error('班级名称重复!')
        else if (res.code === 20006) {
          return this.$message.error('未找到班主任信息!')
        } else if (res.code === 20000) {
          this.addClsDialogVisible = false
          this.getClsList()
          return this.$message.success('添加成功')
        }
      })
    },
    // 展示编辑班级的对话框
    async showClsEditDialog(id) {
      const { data: res } = await this.$http.get('dept/cls/' + id)
      if (res.code !== 20000) {
        return this.$message.error('查询用户信息失败!')
      }
      this.editClsForm = res.data
      // if (this.editClsForm.status === '1') {
      //   this.editClsForm.status = true
      // } else {
      //   this.editClsForm.status = false
      // }
      this.editClsDialogVisible = true
    },
    editClsDialogClosed() {
      this.$refs.editClsFormRef.resetFields()
    },
    updateClsEdit() {
      this.$refs.editClsFormRef.validate(async valid => {
        if (!valid) return
        this.editClsForm.updateBy = window.sessionStorage.getItem('rootname')
        // 设置开关状态按钮
        // if (this.editClsForm.status === true) {
        //   this.editClsForm.status = '1'
        // } else {
        //   this.editClsForm.status = '0'
        // }
        const { data: res } = await this.$http.put(
          'dept/update',
          this.editClsForm
        )
        if (res.code !== 20000) {
          return this.$message.error('更新信息失败!')
        }
        this.editClsDialogVisible = false
        this.getClsList()
        this.$message.success('更新信息成功!')
      })
    },
    async removeClsDialog(id) {
      const { data: res } = await this.$http.get('dept/stu/' + id)
      if (res.data > 0) {
        return this.$message.error('删除失败：存在班级学生!')
      }
      this.delId = id
      this.delClsDialogVisible = true
    },
    async delClsById() {
      const { data: res } = await this.$http.delete('dept/del/' + this.delId)
      if (res.code !== 20000) {
        return this.$message.error('删除分院信息失败!')
      }
      this.delClsDialogVisible = false
      this.getClsList()
      this.$message.success('删除分院信息成功!')
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 12px;
}

.el-row {
  margin-bottom: 10px;
  line-height: 0;
  text-align: left;
}

.el-form-item {
  text-align: left;
}

.el-switch__core {
  margin-left: 10px;
}

.el-select {
  width: 130px;
}
</style>
